<?php

namespace app\chat\controller;

// use app\common\controller\AdminController;
// use app\common\services\annotation\ControllerAnnotation;
// use app\common\services\annotation\NodeAnnotation;
use support\Request; //请求类
use support\Response; //请求类
use think\facade\Db; //数据库类
use app\common\traits\JumpTrait;

/**
 * @ControllerAnnotation(title="group_user")
 */
class IndexController
{
	use JumpTrait;
    
    public function index(Request $request){
        //客服是否存在
        $data['userid'] = session('uid');
        $kf = sysconfig('im','kf');

        if(!$kf or empty($kf)){
            $kf = '-1';
        }else{
            if(!DB::name('user')->where('id',$kf)->find()){
                $kf = '-1';
            }
        }
        //取群聊
        $ls = Db::name('group_user')->where(['userid'=>$data['userid'],'zt'=>"0"])->select();
        $list = array();
		foreach($ls as $lss){
		    $lso = Db::name('group_list')->where('id',$lss['groupid'])->find();
		    $groupuss = Db::name('group_user')->where(['groupid'=>$lss['groupid'],'zt'=>"0"])->select();
		    $grous = [];
		    foreach ($groupuss as $tls){
		        $grous[] = ['tx' => DB::name('user')->where('id',$tls['userid'])->value('tx')];
		    }
		    
		    $lso['groupusers'] = $grous;
		    $lso['groupcount'] = count($lso['groupusers']);
		    array_push($list,$lso);
		}
		//获取私聊消息
		//$sl=Db::query("SELECT * FROM ri_chat col WHERE col.id in (SELECT max(id) FROM ri_chat where fid=".session('userid')." GROUP BY userid) order by id desc");
		//获取好友列表
		$frineds=Db::name('frineds')->where($data)->order('firstletter asc')->select();
		$newFriends = [];
		foreach($frineds as &$lsr){
		    $lso = Db::name('user')->where('id',$lsr['fdid'])->find();
		    if(!$lso){
		        $lsr['fdidimg'] = "/qstatic/image/blackimg.png";
		        $lsr['fdidname'] = "账号已注销";
		    }else{
		        $lsr['fdidimg'] = $lso['tx'];
		        $lsr['fdidname'] = $lso['nickname'];
		    }
		    $newFriends[] = $lsr;
		}

		$frineds_sz=Db::name('frineds')->distinct(true)->where($data)->field('firstletter')->order('firstletter asc')->select();
		
		
		
		//获取新朋友请求数量
		$newsfrineds=Db::name('frineds_log')->where('userid',$data['userid'])->count();
        $userinfo = Db::name('user')->where('id',$data['userid'])->find();
		//ri_frineds_log
	    return view('chat/index/index',['kf'=>$kf,'list'=> $list,'newsfrineds'=>$newsfrineds,'frineds_sz'=>$frineds_sz,'fdzs'=> count($frineds),'userinfo'=>$userinfo,'frineds'=>$newFriends]);
	}
    
    public function sl()
	{
		//获取私聊消息 fid是发方 userid是收方
		$sl=Db::query("SELECT * FROM ri_chat col WHERE col.id in (SELECT max(id) FROM ri_chat where fid=".session('uid')." GROUP BY userid) order by id desc");

		$newsdata='';
		$tempArray = array();
		foreach($sl as $key => $value){ 
           $ts=time()-$value['time'];
           $sls = DB::name('chat')->where(['fid'=>$value['fid'],'userid'=>$value['userid'],'yidu'=>"0"])->count();
           if($sls > 99){
               $sls = "99+";
           }
           //处理只显示对方内容的问题
           //取出反向的聊天内容
            if($value['userid']>$value['fid']){
        		$meme=$value['userid'].$value['fid'];
    		}else{
    			$meme=$value['fid'].$value['userid'];
    		}
    		
    		//这块很反直觉,最后我才发现当时这个补丁是让首页也能显示自己的发言的
            $反向 = DB::name('chat')->where(['merge'=>$meme])->where('type != 99')->order('time desc')->find();
            if($反向){
                $times = $反向['time'];
                $contents = $反向['content'];
            }else{
                $times = $value['time'];
                $contents = $value['content'];
            }
			$tempArray[] = array(
                "id" => $value['id'],
                "fid" => $value['fid'],
                "rank" => $value['rank'],
                "userid" => $value['userid'],
                "name" => username($value['userid']),
                "content" => indexshow($contents),
                "type" => $value['type'],
                "tx" => tx($value['userid']),
                "time" => date("H:i", $times),
                "ts" => $ts,
                "merge" => $value['merge'],
                "timec" => $times,
                "sl" => $sls
            );
			
		} 
        // 使用 usort 函数进行排序
        usort($tempArray, function($a, $b) {
            return $b['timec'] -$a['timec'];
        });
       $返回 = array();
       $返回['sl'] = $tempArray;
       //群聊部分
       $history = DB::name('group_history')->where(['uid'=>session('uid')])->select();
       foreach ($history as $ls){
           $sl = DB::name('group_chat')->where('fid',$ls['groupid'])->where('id','>',$ls['groupchatid'])->count();
           if($sl > 99){
               $sl = "99+";
           }
           $返回['ql'][]= ['id'=>$ls['groupid'],'sl'=>$sl];
       }
         return json($返回);
        //echo(json_encode($返回,JSON_UNESCAPED_UNICODE));
	}
   	public function addfd(Request $request){
		$list=[];
		
		if($request->post('name') != NULL){
		    $list=Db::name('user')
			->where('name','like','%'.$request->post('name').'%')
			->select();
		}
	    return view('chat/index/addfd',['list'=>$list]);
	}
    public function fdinfo(Request $request){
        $fdinfo=Db::name('user')->where('id',$request->get('id'))->find();
        return view('chat/index/fdinfo',['fdinfo'=>$fdinfo]);
    }
    //添加好友
	public function addhy(Request $request){
		if($request->get('id'))
		{
			$info=Db::name('user')
			->where('id',$request->get('id'))
			->find();
		}
		if(!$info)  $this->error('用户不存在');
		//好友添加
		$data['userid']=session('uid');//用户名转化为ID
		$data['fdid']=$info['id'];
		$fdinfo=Db::name('frineds')->where($data)->find();
		if($fdinfo){
			//是否已被添加为好友
			if($fdinfo['rank']==0){
				//更改状态完成好友添加
			}else{
			return $this->error('已经是好友');
			exit;
			}
		}else{
			//新好友
			$data['fdname']=username($info['id']);
			$data['firstletter']=getFirstCharter(username($info['id']));
			$data['rank']=1;
			Db::name('frineds')->insert($data);
		}
		//发送好友请求
		$dataqq['userid']=$info['id'];//用户名转化为ID
		$dataqq['fdid']=session('uid');
		if(!Db::name('frineds')->where($dataqq)->find()){
			$dataqq['time']=time();
			Db::name('frineds_log')->insert($dataqq);
		}
		return $this->success('加好友成功',[], '/chat');
	}
	 public function chat(Request $request)
    {
        
		$privateinfo=Db::name('user')->where(array('id'=>$request->get('id')))->find();
		if(!$privateinfo){
            return $this->error('用户已注销',[], '/chat');
        }
		DB::name('chat')->where(['userid'=>$request->get('id'),'fid'=>session('uid'),'yidu'=>"0"])->update(['yidu'=>'1']);
		$userinfo = DB::name('user')->where('id',session('uid'))->find();
        return view('chat/index/chat',['privateinfo'=>$privateinfo,'userinfo'=>$userinfo]);
    }
    public function pchat(Request $request){
        $data['userid']=$request->post('id');
		$data['content']=htmlspecialchars($request->post('content'));
		$data['fid']=$request->post('fid');
		$data['time']=time();
		//私聊识别标识符
		if($request->post('id')>$request->post('fid')){
		$data['merge']=$request->post('id').$request->post('fid');
		}else{
			$data['merge']=$request->post('fid').$request->post('id');
		}
		$startTimestamp = strtotime(date('Y-m-d H:i:00'));
        $endTimestamp = strtotime(date('Y-m-d H:i:59'));
        $counts  = DB::name('chat')->where(['merge'=>$data['merge'],'userid'=>$data['userid']])->where('time >= '.$startTimestamp.' AND time <= '.$endTimestamp)->count();
        if($counts > 30){
            return 's9';
            exit;
        }
		//消息提示
		$where['userid']=$data['userid'];
		$where['fdid']=$data['fid'];
		$update['time']=$data['time'];
		$update['zt']='1';
		Db::name('frineds')->where($where)->update($update);
		//检查是否需要插入时间,先取出上一条时间
        $sctm = Db::name('chat')->where(['merge'=>$data['merge']]) ->order('time', 'desc')->find();
        if($sctm){
            $时间差 = abs(time() - (int)$sctm['time']); // 时间戳差异的秒数
            $时间差分钟 = round($时间差 / 60); // 转换为分钟并四舍五入
            if($时间差分钟 >= 10){
                $date = date("Y年m月d日", time());
                $hour = date("H",  time());
                $minute = date("i",  time());
                $timeOfDay = ($hour >= 12) ? "晚上" : "上午";
                if ($hour > 12) {
                    $hour -= 12;
                }
                $格式化后时间 = $date . " " . $timeOfDay . $hour . ":" . $minute;
                DB::name('chat')->insert(['userid'=>0,'fid'=>"",'type'=>99,'merge'=>$data['merge'],'yidu'=>'1','time'=>time(),'content'=>'<li class="time"><span>'.$格式化后时间.'</span></li>']);
            }
        }else{
            $date = date("Y年m月d日", time());
            $hour = date("H",  time());
            $minute = date("i",  time());
            $timeOfDay = ($hour >= 12) ? "晚上" : "上午";
            if ($hour > 12) {
                $hour -= 12;
            }
            $格式化后时间 = $date . " " . $timeOfDay . $hour . ":" . $minute;
            DB::name('chat')->insert(['userid'=>0,'fid'=>"",'type'=>99,'merge'=>$data['merge'],'yidu'=>'1','time'=>time(),'content'=>'<li class="time"><span>'.$格式化后时间.'</span></li>']);
        }
		$orderid=Db::name('chat')->insertGetId($data);
		//对方未回复首页就不显示,所以插入一条空数据
		if(Db::name('chat')->where(['userid'=>$data['fid'],'fid'=>$data['userid']])->count() < 1){
		    Db::name('chat')->insert(['userid'=>$data['fid'],'fid'=>$data['userid'],'merge'=>$data['merge'],'type'=>'99','content'=>'<a></a>','yidu'=>'1','time'=>time()]);
		}
		return $orderid;
    }
    public function chatmessage(Request $request)
	{
		if($request->post('fid')>$request->post('userid')){
		$data['merge']=$request->post('fid').$request->post('userid');
		}else{
			$data['merge']=$request->post('userid').$request->post('fid');
		}
		$groupmessage=Db::name('chat')->where($data)->order('id desc')->limit(100)->select();
		if(!$groupmessage) return '';
		$collection = new \think\Collection($groupmessage);
        $array = $collection->toArray();
		$groupmessage=array_reverse($array);//数组反向输出
		$newsdata='';
		foreach($groupmessage as $key => $value){ 
			$newsdata.='{"id":"'.$value['id'].'","fid":"'.$value['fid'].'","rank":"'.$value['rank'].'","userid":"'.$value['userid'].'","name":"'.username($value['userid']).'","content":"'.glnews(htmlspecialchars_decode($value['content'])).'","type":"'.$value['type'].'","tx":"'.tx($value['userid']).'","time":"'.date('H:i:s',$value['time']).'"},';
		} 
		$newsdata=substr($newsdata,0,strlen($newsdata)-1); 
		$newsdata= '['.$newsdata.']';
		
		DB::name('chat')->where(['userid'=>input('post.fid'),'fid'=>input('post.userid'),'yidu'=>"0"])->update(['yidu'=>'1']);
		return json($newsdata);
		//群组消息
	}
	public function chatpic(Request $request){
        $rere =  $request->rawBody();
        $base64_string = preg_replace('#^data:image/\w+;base64,#i', '', $rere);
        $decodedData = base64_decode($base64_string);
        // 获取解码后数据的前几个字节（通常是足以确定文件类型的）
        $bytes = substr($decodedData, 0, 4);
        
        // 根据文件类型标识符进行检查
        $fileType = '';
        if (strpos($bytes, "\xFF\xD8\xFF") === 0) {
            $fileType = 'jpg'; // JPEG 图片
        } elseif (strpos($bytes, "\x89\x50\x4E\x47") === 0) {
            $fileType = 'png'; // PNG 图片
        } elseif (strpos($bytes, "\x47\x49\x46\x38") === 0) {
            $fileType = 'gif'; // GIF 图片
        } elseif (strpos($bytes, "BM") === 0) {
            $fileType = 'bmp'; // BMP 图片
        } else {
            return '上传格式错误';
        }
		mkml('./public/uploadimg/'.date("Y-m-d"));//文件目录是否存在不存在则生成
		$tmp_file = 'uploadimg/'.date("Y-m-d").'/'.random(5).time().'.'.$fileType;
		$tmp_file_1 = './public/'.$tmp_file;
		file_put_contents($tmp_file_1, $decodedData);
		$txinfo='<img class="img__pic" src="/'.$tmp_file.'" />'; 
		$data['userid']=$request->get('id');
		$data['type']='1';//1表示图片
		$data['content']=htmlspecialchars($txinfo);
		$data['fid']=$request->get('fid');
		//私聊识别标识符
		if($request->get('id')>$request->get('fid')){
		$data['merge']=$request->get('id').$request->get('fid');
		}else{
			$data['merge']=$request->get('fid').$request->get('id');
		}
		$data['time']=time();
		$orderid=Db::name('chat')->insertGetId($data);
		return $txinfo;
	}
	//群组聊天
	public function groupchat(Request $request)
    {
		//获取群信息

		$groupinfo=Db::name('group_list')->where('id',$request->get('id'))->find();
		if(!$groupinfo){
			return $this->error('群组不存在');
			exit;
		}
		if($groupinfo['rank']==0){
			return $this->error('本群还未通过审核');
			exit;
		}
		//用户是否有权限登陆本群组
		$userid=session('uid');
		$data['groupid']=$request->get('id');
		$data['userid']=$userid;
		$groupuser=Db::name('group_user')->where($data)->find();
		if($groupuser){
			
			if($groupuser['zt']=='1'){
				return $this->error('禁止访问群组');
			exit;
			}
			
		}else{
		    return $this->error('禁止访问群组');
			//第一次进群用户自动加入群组
			//$orderid=Db::name('groupuser')->insertGetId($data);
		}
		//判断是否为群主提供权限
		if($groupinfo['userid']==$userid){
			$qz = 1;
		}else{
			$qz = 0;
		}

        return view('chat/index/groupchat',['groupinfo'=>$groupinfo,'qz'=>$qz]);
    }
	//群消息心跳
	public function groupmessage(Request $request)
	{
		$data['fid']=$request->post('fid');
		$groupmessage=Db::name('group_chat')->where($data)->order('id desc')->limit(100)->select();
		if(!$groupmessage) return;
		$collection = new \think\Collection($groupmessage);
        $array = $collection->toArray();
		$groupmessage=array_reverse($array);//数组反向输出
		$newsdata='';
		foreach($groupmessage as $key => $value){ 

           $ts=time()-$value['time'];
			$newsdata.='{"id":"'.$value['id'].'","fid":"'.$value['fid'].'","rank":"'.$value['rank'].'","userid":"'.$value['userid'].'","name":"'.username($value['userid']).'","content":"'.glnews(htmlspecialchars_decode($value['content'])).'","type":"'.$value['type'].'","tx":"'.tx($value['userid']).'","time":"'.$value['time'].'","ts":"'.$ts.'"},';
		}
		
		$newsdata=substr($newsdata,0,strlen($newsdata)-1); 
		$newsdata= '['.$newsdata.']';
		
		//记录最新消息到群组记录
		//取最后一条
		$endmess = end($groupmessage);
		$返回 = DB::name('group_history')->where(['uid'=>$request->post('userid'),'groupid'=>$request->post('fid')])->find();
		if($返回){
		    //更新已经有的记录
		    if($返回['groupchatid'] != $endmess['id']){
		        DB::name('group_history')->where(['uid'=>$request->post('userid'),'groupid'=>$request->post('fid')])->update(['groupchatid'=>$endmess['id']]);
		    }
		}else{
		    //没有记录插入一条
		    DB::name('group_history')->insert(['groupchatid'=>$endmess['id'],'uid'=>$request->post('userid'),'groupid'=>$request->post('fid')]);
		}

		
		return $newsdata;
        
	}
	public function group(Request $request)
	{
		//查询聊天室是否可发言
			$groupdata['id']=$request->post('fid');//群ID
			//$datainfo['userid']=userid(cookie('name'));//是否群主
			$info=Db::name('group_list')->where($groupdata)->find();
			if($info['status']=='0'){
				//群权限认证通过
				$data2['groupid']=$request->post('fid');
				$data2['userid']=session('name');
				$groupuserinfo=Db::name('group_user')->where($data2)->find();
				if($groupuserinfo){
					if($groupuserinfo['zt']=='1'){
					echo 's2';
					exit;
					}
				}
			}else{
				return 's1';
				exit;
			}
        //查询发言频率 s9
        $startTimestamp = strtotime(date('Y-m-d H:i:00'));
        $endTimestamp = strtotime(date('Y-m-d H:i:59'));
        $counts  = DB::name('group_chat')->where(['fid'=>$groupdata['id'],'userid'=>$request->post('id')])->where('time >= '.$startTimestamp.' AND time <= '.$endTimestamp)->count();
        if($counts > 30){
            return 's9';
            exit;
        }
        
		$data['userid']=$request->post('id');
		$data['content']=htmlspecialchars($request->post('content'));
		if($info['userid']==$data['userid']){
			//群主消息
			$data['rank']=1;
		}
		$data['fid']=$request->post('fid');
		$data['time']=time();

        //检查是否需要插入时间,先取出上一条时间
        $sctm = Db::name('group_chat')->where(['fid'=>$groupdata['id']]) ->order('time', 'desc')->find();
        $时间差 = abs(time() - (int)$sctm['time']); // 时间戳差异的秒数
        $时间差分钟 = round($时间差 / 60); // 转换为分钟并四舍五入
        if($时间差分钟 >= 10){
            $date = date("Y年m月d日", time());
            $hour = date("H",  time());
            $minute = date("i",  time());
            $timeOfDay = ($hour >= 12) ? "晚上" : "上午";
            if ($hour > 12) {
                $hour -= 12;
            }
            $格式化后时间 = $date . " " . $timeOfDay . $hour . ":" . $minute;
            DB::name('group_chat')->insert(['userid'=>0,'fid'=>$groupdata['id'],'type'=>3,'time'=>time(),'content'=>'<li class="time"><span>'.$格式化后时间.'</span></li>']);
        }

		//在信息发送后补机器人消息
        //检索可用的机器人
        $botcon = $request->post('content');
        $uinfo = DB::name('user')->where(['id'=>$request->post('id')])->find();
		$botlist = DB::name('bot_list')->where(['groupid'=>$request->post('fid'),'status'=>"1"])->select();

		if(count($botlist) == 0){
		    $orderid=Db::name('group_chat')->insertGetId($data);
		}else{
		    foreach ($botlist as $ls){
    		    $bottextlist = DB::name('bot_text')->where(['botid'=>$ls['id']])->select();
    		    $返回类型 = 0;
    		    $返回文本 = "";
    		    foreach ($bottextlist as $textls){
    		        //如果匹配了文本
    		        if(strpos($botcon, $textls['gjz']) != false){
    		            if($textls['type'] == "1"){
    		                $返回类型 = 1;
    		                $返回文本 =  htmlspecialchars("<p style='color:#006efe'>@".$uinfo['nickname'].'</p><p>'.$textls['value'].'</p>');
    		                DB::name('bot_log')->insert(['gjz'=>$textls['gjz'],'groupid'=>$request->post('fid'),'botid'=>$ls['id'],'uid'=>$uinfo['id']."|".$uinfo['nickname'],'ufy'=>htmlspecialchars($request->post('content')),'type'=>$textls['type'],'cz'=>'回复:'.$返回文本,'time'=>time()]);
    		            }elseif($textls['type'] == "2"){
    		                $data['content']=htmlspecialchars(str_replace($textls['gjz'],$textls['value'],$request->post('content')));
                            $返回类型 = 2;
                            DB::name('bot_log')->insert(['gjz'=>$textls['gjz'],'groupid'=>$request->post('fid'),'botid'=>$ls['id'],'uid'=>$uinfo['id']."|".$uinfo['nickname'],'ufy'=>htmlspecialchars($request->post('content')),'type'=>$textls['type'],'cz'=>'回复:'.$data['content'],'time'=>time()]);
    		            }elseif($textls['type'] == "3"){
    		                $返回类型 = 3;
    		                DB::name('bot_log')->insert(['gjz'=>$textls['gjz'],'groupid'=>$request->post('fid'),'botid'=>$ls['id'],'uid'=>$uinfo['id']."|".$uinfo['nickname'],'ufy'=>htmlspecialchars($request->post('content')),'type'=>$textls['type'],'cz'=>'撤回消息','time'=>time()]);
    		            }
    		        }
    		        
    		    }
    		    
    		    if($返回类型 == 0){
    		        $orderid=Db::name('group_chat')->insertGetId($data);
    		    }elseif($返回类型 == 1){
    		        //正常发送
                    $orderid=Db::name('group_chat')->insertGetId($data);
                    //客服风回复
                    DB::name('group_chat')->insert(['userid'=>0,'fid'=>$request->post('fid'),'type'=>4,'time'=>time(),'content'=>$返回文本]);
    		    }elseif($返回类型 == 2){
    		        //替换型回复
                    $orderid=Db::name('group_chat')->insertGetId($data);
    		    }elseif($返回类型 == 3){
    		        DB::name('group_chat')->insert(['userid'=>0,'fid'=>$groupdata['id'],'type'=>3,'time'=>time(),'content'=>'<li class="time"><span>群聊管家撤回了'.$uinfo['nickname'].'的一条消息</span></li>']);
    		        $orderid = 0;
    		    }
    		    
    		    
    		}
		}

		return $orderid;
		//echo '群组';
	}

	public function grouppic(Request $request){
		//查询聊天室是否可发言
		$groupdata['id']=$request->get('fid');//群ID
		//$datainfo['userid']=userid(cookie('name'));//是否群主
		$info=Db::name('group_list')->where($groupdata)->find();
		if($info['status']=='0'){
			//群权限认证通过
			$data2['groupid']=$request->get('fid');
			$data2['userid']=session('name');
			$groupuserinfo=Db::name('group_user')->where($data2)->find();
			if($groupuserinfo){
				if($groupuserinfo['zt']=='1'){
				echo 's2';
				exit;
				}
			}
		}else{
			return 's1';
		}

		$rere =  $request->rawBody();
        $base64_string = preg_replace('#^data:image/\w+;base64,#i', '', $rere);
        $decodedData = base64_decode($base64_string);
        // 获取解码后数据的前几个字节（通常是足以确定文件类型的）
        $bytes = substr($decodedData, 0, 4);
        
        // 根据文件类型标识符进行检查
        $fileType = '';
        if (strpos($bytes, "\xFF\xD8\xFF") === 0) {
            $fileType = 'jpg'; // JPEG 图片
        } elseif (strpos($bytes, "\x89\x50\x4E\x47") === 0) {
            $fileType = 'png'; // PNG 图片
        } elseif (strpos($bytes, "\x47\x49\x46\x38") === 0) {
            $fileType = 'gif'; // GIF 图片
        } elseif (strpos($bytes, "BM") === 0) {
            $fileType = 'bmp'; // BMP 图片
        } else {
            return '上传格式错误';
        }
		mkml('./public/uploadimg/'.date("Y-m-d"));//文件目录是否存在不存在则生成
		$tmp_file = 'uploadimg/'.date("Y-m-d").'/'.random(5).time().'.'.$fileType;
		$tmp_file_1 = './public/'.$tmp_file;
		file_put_contents($tmp_file_1, $decodedData);
		
		//用户聊天记录
		//判断是否为写入
		//将上传后的图片写入用户信息中
		//$data_str= '<a href="/'.$tmp_file.'"><img class="connetimg" src="/'.$tmp_file.'"></a>';
		//写入数据库

		//$txinfo='<img width="36" height="36" src="/'.$tmp_file.'" class="uimg" id="uptpztzt"><input type="hidden" name="grouptx" value ="/'.$tmp_file.'"/>';
		$txinfo='<div class="image"><img class="img__pic" src="/'.$tmp_file.'" /></div>'; 
		$data['userid']=$request->get('id');
		$data['type']='1';//1表示图片
		if($info['userid']==$data['userid']){
			//群主消息
			$data['rank']=1;
		}
		$data['content']=htmlspecialchars($txinfo);
		$data['fid']=$request->get('fid');
		$data['time']=time();
		$orderid=Db::name('group_chat')->insertGetId($data);
		return $txinfo;
	}
	//将用户踢出群组
	public function grouplogout(Request $request){
		$data['id']=$request->post('fid');
		$data['userid']=session ('name');
		$info=Db::name('group_list')->where($data)->find();
			if($info){
				//权限审核通过
				$datainfo['groupid']=$request->post('fid');
				$datainfo['userid']=$request->post('id');;
				$updata['zt']='1';
				$ls = Db::name('group_user')->where($datainfo)->update($updata);
				if(!$ls){
				    $updata['groupid']=$request->post('fid');
				    $updata['userid']=$request->post('id');;
				    $ls = Db::name('group_user')->insert($updata);
				}
				return '1';
			}else{
				//没有权限
				return '0';
			}
	}

	//删除群组用户聊天记录
	public function groupuserxx(Request $request){
		$data['id']=$request->post('fid');
		$data['userid']=session ('name');
		$info=Db::name('group_list')->where($data)->find();
			if($info){
				//权限审核通过
				$datainfo['fid']=$request->post('fid');
				$datainfo['userid']=$request->post('id');;
				Db::name('group_chat')->where($datainfo)->delete();
				return '1';
			}else{
				//没有权限
				return '0';
			}
		
	}

	public function groupinfo(Request $request){
		//获取群信息
		$groupinfo=Db::name('group_list')->where('id',$request->get('id'))->find();
		if(!$groupinfo){
			return $this->error('群组不存在');
			exit;
		}
		//获取群成员列表
		$list=Db::name('group_user')
			->where('groupid',$request->get('id'))
			->select();
		$data['id']=$request->get('id');
		$data['userid']=session('name');
		$info=Db::name('group_list')->where($data)->find();
		if($info){
			$qz = '1';
			}else{
				$qz = '0';
			}
		return view('chat/index/groupinfo',['qz'=>$qz,'list'=>$list,'groupinfo'=>$groupinfo]);
	}

	//清空群消息
	public function groupqk(Request $request){
		if($request->post('userid')){
			$data['id']=$request->post('userid');
			$data['userid']=session('uid');
			$info=Db::name('group_list')->where($data)->find();
			if($info){
				//群权限认证通过
				Db::name('group_chat')->where('fid',$data['id'])->delete();
				return '1';
			}else{
				return '0';
			}
		}
	}
	//删除群
	public function groupdel(Request $request){
		if($request->post('userid')){
			$data['id']=$request->post('userid');
			$data['userid']=session('uid');
			$info=Db::name('group_list')->where($data)->find();
			if($info){
				//群权限认证通过
				Db::name('group_list')->where('id',$data['id'])->delete();
				Db::name('group_chat')->where('fid',$data['id'])->delete();
				Db::name('group_user')->where('groupid',$data['id'])->delete();
				return '1';
			}else{
				return '0';
			}
		}
	}

	//更改群状态
	public function groupzt(Request $request){
		if($request->post('groupid')){
			$data['id']=$request->post('groupid');
			$data['userid']=session('uid');
			$info=Db::name('group_list')->where($data)->find();
			if($info){
				//群权限认证通过
				if($info['status']==0){
					$updata['status']='1';
				}else{
					$updata['status']='0';
				}
				Db::name('group_list')->where('id',$data['id'])->update($updata);
				return $updata['status'];
			}else{
				return '2';
			}
		}
	}

	public function groupaddu(Request $request){
	    $user = $request->post('user');
	    $ls = DB::name('user')->where(['name'=>$user])->find();
	    if(!$ls){
	        return $this->error("账号不存在");
	    }else{
	        if(DB::name('group_user')->where(['userid'=>$ls['id'],'groupid'=>$request->post('group')])->count() > 0){
	            return $this->error("对方已经在群聊中");
	        }
	        DB::name('group_user')->insert(['userid'=>$ls['id'],'groupid'=>$request->post('group'),'zt'=>0]);
	        DB::name('group_chat')->insert(['userid'=>0,'fid'=>$request->post('group'),'type'=>3,'time'=>time(),'content'=>'<li class="notice"><span>"<a href="/qchat/index/fdinfo.html?id='.$ls['id'].'">'.$ls['nickname'].'</a>"通过"<a href="/chat/fdinfo?id='.session('uid').'">'.session('name').'</a>"的邀请加入群聊</span></li>']);
	        
	        return $this->success("操作成功!");
	    }
	    
	}

	public function newsfd(Request $request){
        $list=Db::name('frineds_log')
			->where('userid',session('uid'))
			->select();
		return view('chat/index/newsfd',['list'=>$list]);
		
	}
	public function fdsh(Request $request){
		//审核通过加为好友
		if($request->post('id'))
		{
			$info=Db::name('frineds_log')
			->where('id',$request->post('id'))
			->find();
		}
		if(!$info)  return '2';
		//好友添加
		$data['userid']=$info['userid'];//用户名转化为ID
		$data['fdid']=$info['fdid'];
		if($request->post('type') == '0'){
		    Db::name('frineds_log')->where('id',$info['id'])->delete();
			return '4';
		}
		if(Db::name('frineds')->where($data)->find()){
		    //删除请求记录
		    Db::name('frineds_log')->where('id',$info['id'])->delete();
			return '0';
		}else{
			$data['fdname']=username($info['fdid']);
			$data['firstletter']=getFirstCharter(username($info['fdid']));
			$data['zt']='1';
			Db::name('frineds')->insert($data);
			//删除请求记录
		    Db::name('frineds_log')->where('id',$info['id'])->delete();
			return '1';
		}

	}
		//群列表
	public function listgroup(){
		$list=Db::name('group_user')
			->where('userid',session('uid'))
			->select();
		return view('chat/index/listgroup',['list'=>$list]);
	}
	public function myinfo(){
	    return view('chat/index/myinfo');
	}
	public function mytx(request $request){
		$rere =  $request->rawBody();
        $base64_string = preg_replace('#^data:image/\w+;base64,#i', '', $rere);
        $decodedData = base64_decode($base64_string);
        // 获取解码后数据的前几个字节（通常是足以确定文件类型的）
        $bytes = substr($decodedData, 0, 4);
        
        // 根据文件类型标识符进行检查
        $fileType = '';
        if (strpos($bytes, "\xFF\xD8\xFF") === 0) {
            $fileType = 'jpg'; // JPEG 图片
        } elseif (strpos($bytes, "\x89\x50\x4E\x47") === 0) {
            $fileType = 'png'; // PNG 图片
        } elseif (strpos($bytes, "\x47\x49\x46\x38") === 0) {
            $fileType = 'gif'; // GIF 图片
        } elseif (strpos($bytes, "BM") === 0) {
            $fileType = 'bmp'; // BMP 图片
        } else {
            return '上传格式错误';
        }
		mkml('./public/uploadimg/'.date("Y-m-d"));//文件目录是否存在不存在则生成
		$tmp_file = 'uploadimg/'.date("Y-m-d").'/'.random(5).time().'.'.$fileType;
		$tmp_file_1 = './public/'.$tmp_file;
		file_put_contents($tmp_file_1, $decodedData);
		
		//用户聊天记录
		//判断是否为写入
		//将上传后的图片写入用户信息中
		$data_str= '<a><img class="connetimg" src="/'.$tmp_file.'"></a>';
		$data['tx']="/".$tmp_file;
		Db::name('user')->where('id',session('uid'))->update($data); 
		$txinfo='<img width="36" height="36" src="/'.$tmp_file.'" class="uimg" id="uptpztzt">';
		return $txinfo;
	
	}
	public function grouptx(request $request){
		$rere =  $request->rawBody();
        $base64_string = preg_replace('#^data:image/\w+;base64,#i', '', $rere);
        $decodedData = base64_decode($base64_string);
        // 获取解码后数据的前几个字节（通常是足以确定文件类型的）
        $bytes = substr($decodedData, 0, 4);
        
        // 根据文件类型标识符进行检查
        $fileType = '';
        if (strpos($bytes, "\xFF\xD8\xFF") === 0) {
            $fileType = 'jpg'; // JPEG 图片
        } elseif (strpos($bytes, "\x89\x50\x4E\x47") === 0) {
            $fileType = 'png'; // PNG 图片
        } elseif (strpos($bytes, "\x47\x49\x46\x38") === 0) {
            $fileType = 'gif'; // GIF 图片
        } elseif (strpos($bytes, "BM") === 0) {
            $fileType = 'bmp'; // BMP 图片
        } else {
            return '上传格式错误';
        }
		mkml('./public/uploadimg/'.date("Y-m-d"));//文件目录是否存在不存在则生成
		$tmp_file = 'uploadimg/'.date("Y-m-d").'/'.random(5).time().'.'.$fileType;
		$tmp_file_1 = './public/'.$tmp_file;
		file_put_contents($tmp_file_1, $decodedData);
		//用户聊天记录
		//判断是否为写入
		//将上传后的图片写入用户信息中
		//$data_str= '<a href="/'.$tmp_file.'"><img class="connetimg" src="/'.$tmp_file.'"></a>';
		//写入数据库

		$txinfo='<img width="36" height="36" src="/'.$tmp_file.'" class="uimg" id="uptpztzt"><input type="hidden" name="grouptx" value ="/'.$tmp_file.'"/>';
		//$txinfo='<img class="img__pic" src="/'.$tmp_file.'" />'; 

		return $txinfo;
	}
	
	public function updatename(Request $request){
	    if(!$request->post('name')){
	        $this->error('名称不正确');
	    }
	    $返回 = DB::name('user')->where(['id'=>session('uid')])->update(['nickname'=>$request->post('name')]);
	    if($返回){
	        return $this->success('名称更换成功!');
	    }else{
	        return$this->error('更换失败,请重试');
	    }
	}
	
		public function addgroup(Request $request){
		if($request->post('groupname')){
			$data['userid']=session('uid');
			$data['title']=$request->post('groupname');
			$data['content']=$request->post('groupinfo');
			//$data['img']=$request->post('grouptx');
			$data['fid']='1';
			//设置群状态
			$data['rank']='1';//是否显示
			$data['time']=time();
			$newsid=Db::name('group_list')->insertGetId($data);
			
			//自己加入群聊
			Db::name('group_user')->insert(['groupid'=>$newsid,'userid'=>$data['userid']]);

			if($data['rank']==0){
			    return $this->success('群建立成功等待审核通过后可显示');
			}else{
				return $this->success('新增成功');
			}

		}
		return view('chat/index/addgroup');
	}
}
